package com.common.convert;

import com.common.convert.impl.OfficeConverter;
import com.common.convert.param.ConvertInput;
import com.common.convert.param.ConvertResult;
import lombok.Data;

import java.util.*;

/**
 * @author lxw
 */
@Data
public class ConverterRouter implements Converter {

    private static Map<Object, List<Converter>> CONVERTER_MAP = new LinkedHashMap<>();

    private static Map<String, Set<String>> SUPPORT_FROM_TO_MAP = new LinkedHashMap<>();

    private static Set<FormatSupport> FORMAT_SUPPORTS = new HashSet<>();

    static {
        register(new OfficeConverter());
    }

    public ConvertResult convert(ConvertInput convertInput, String outType) {
        FormatSupport formatSupport = new FormatSupport(convertInput.getInputType(), outType);
        if (CONVERTER_MAP.containsKey(formatSupport)) {
            List<Converter> converters = CONVERTER_MAP.get(formatSupport);
            Exception exception = null;
            for (Converter converter : converters) {
                try {
                    return converter.convert(convertInput, outType);
                } catch (Exception e) {
                    exception = e;
                    e.printStackTrace();
                }
            }
            throw new ConvertException(exception);
        }
        throw new ConvertException("不支持从：" + convertInput.getInputType() + "转成：" + outType);
    }

    @Override
    public Set<FormatSupport> supports() {
        return FORMAT_SUPPORTS;
    }

    private static void register(Converter converter) {
        FORMAT_SUPPORTS.addAll(converter.supports());
        converter.supports().forEach(formatSupport -> {
            List<Converter> converters = CONVERTER_MAP.get(formatSupport);
            if (converters == null) {
                converters = new ArrayList<>();
                converters.add(converter);
                CONVERTER_MAP.put(formatSupport, converters);
            } else {
                converters.add(converter);
            }
        });
    }

}
